import { getModelData } from '@renderer/api'
import { useViewportStore } from '@renderer/stores/viewport'
import emiter from '@renderer/utils/mitt'
import { ElLoading } from 'element-plus'
import { storeToRefs } from 'pinia'
import { ObjectLoader } from '@renderer/utils/ObjectLoader'
import { nextTick } from 'vue'
import { useHistory } from '@renderer/utils/useHistory'
import { useFocusObject } from '@renderer/utils/useFocusObject'
import { useAddTools } from '@renderer/utils/useAddTools'

const viewportStore = useViewportStore()
const { publicGroup } = storeToRefs(viewportStore)
const loader = new ObjectLoader()
const { commitHistory } = useHistory()
const { focusObject } = useFocusObject()
const { hasGroup, createdLabel } = useAddTools()
export default async function () {
  const loading = ElLoading.service({
    lock: true,
    text: 'Loading',
    background: 'rgba(0, 0, 0, 0.7)'
  })
  // 获取导线数据
  const { data } = await getModelData()
  if (data.modelInfo && data.modelInfo[0]) {
    const sceneNodes = loader.parse(data.modelInfo[0])
    if (sceneNodes.children?.length) {
      publicGroup.value?.add(...sceneNodes.children)
      publicGroup.value?.children.forEach((group) => {
        if (group.name === '设备') {
          group.children.forEach((node) => {
            const label = createdLabel(node.name, node.name)
            label.name = node.name
            node.add(label)
          })
        }
      })
    }
    nextTick(() => {
      emiter.emit('viewChange')
      loading.close()
      commitHistory('导入巷道数据', 'import')
      const group = hasGroup('巷道', false)
      if (group) {
        focusObject(group)
      }
    })
  } else {
    loading.close()
  }
}
